<template>
  <view class="container">
    <ve-card :title="feeRecord.feeName" type="none" fold>
      <template #status>
        <view class="status-2" v-if="feeRecord.feeTypeName">{{ feeRecord.feeTypeName }}</view>
        <view class="status-1" v-if="feeRecord.costTypeName">{{ feeRecord.costTypeName }}</view>
      </template>
      <ve-cell-price label="应付金额" :value="feeRecord.receiveAmount"></ve-cell-price>
      <ve-cell-price label="待付金额" :value="feeRecord.receivedNotAmount"></ve-cell-price>

      <block v-if="feeCategory == 1">
        <ve-cell-val label="保养单号" :value="feeRecord.businesCode" />
        <ve-cell-val label="修理厂" :value="feeRecord.supplierName" />
        <ve-cell-val label="车牌号" :value="feeRecord.carLicenseNo" />
        <ve-cell-val label="保养日期" :value="feeRecord.startTime" formate="date" />
        <ve-cell-val label="费用备注" :value="feeRecord.remark" />
      </block>
      <block v-else-if="feeCategory == 2">
        <ve-cell-val label="维修单号" :value="feeRecord.businesCode" />
        <ve-cell-val label="修理厂" :value="feeRecord.supplierName" />
        <ve-cell-val label="车牌号" :value="feeRecord.carLicenseNo" />
        <ve-cell label="维修周期">{{ feeRecord.startTime }} - {{ feeRecord.endTime }}</ve-cell>
        <ve-cell label="">
          <text class="c3 fs30 fw400">时长：{{ feeRecord.rentDays || '-' }}</text>
        </ve-cell>
      </block>
      <block v-else-if="feeCategory == 3">
        <ve-cell-val label="年检单号" :value="feeRecord.businesCode" />
        <ve-cell-val label="年检厂" :value="feeRecord.supplierName" />
        <ve-cell-val label="车牌号" :value="feeRecord.carLicenseNo" />
        <ve-cell-val label="年检日期" :value="feeRecord.startTime" formate="date" />
        <ve-cell-val label="费用备注" :value="feeRecord.remark" />
      </block>
      <!-- 表格 -->
      <FeeTable :record="feeRecord" v-if="feeCategory == 2"></FeeTable>
      <ve-gap size="24"></ve-gap>
    </ve-card>
    <!-- 表单 -->
    <ve-form ref="veFormRef" :model="form" :rules="rules">
      <ve-card type="none" fold v-model:initFold="foldStatus.fold1">
        <ve-form-item label="结算时间" required prop="paymentTime">
          <ve-date-picker v-model="form.paymentTime" title="时间"></ve-date-picker>
        </ve-form-item>
        <ve-form-item
          label="结算方式"
          required
          prop="paymentWay"
          labelTooltipContent="结算方式支持在系统管理菜单下的【结算方式管理】页面进行配置。"
        >
          <ve-picker-inline
            v-model="form.paymentWay"
            placeholder="请选择"
            :range="paywayEnum"
            unit="arrowRight"
            @change="typeChange"
          ></ve-picker-inline>
        </ve-form-item>

        <ve-form-item label="结算账号" labelTooltipContent="结算账号支持在系统管理菜单下的【结算方式管理】页面进行配置。">
          <ve-picker-inline v-model="form.account" placeholder="请选择" :range="accountList" unit="arrowRight" />
        </ve-form-item>

        <ve-form-item label="结算金额" unit="元">
          <ve-input-number v-model="form.actualAmount" :precision="2" disabled />
        </ve-form-item>
        <ve-form-item label="供应商名称" required prop="customerName">
          <remote-select
            v-if="feeCategory == 1"
            type="supplierMain"
            :label="form.customerName"
            v-model="form.customerId"
            @change="customerChange"
          />
          <remote-select
            v-if="feeCategory == 2"
            type="supplierRepair"
            :label="form.customerName"
            v-model="form.customerId"
            @change="customerChange"
          />
          <remote-select
            v-if="feeCategory == 3"
            type="supplierInspects"
            :label="form.customerName"
            v-model="form.customerId"
            @change="customerChange"
          />
        </ve-form-item>
        <ve-form-item label="供应商收款账号">
          <ve-input v-model="form.customerAccount" placeholder="请输入" :maxlength="20" />
        </ve-form-item>
        <ve-form-item label="结算备注" labelPosition="top">
          <ve-input type="textarea" v-model="form.settlementRemark" placeholder="请输入备注" :maxlength="200" />
        </ve-form-item>
        <ve-form-item label="结算凭证" labelPosition="top" :borderBottom="false" prop="fileIdList">
          <view>
            <ve-upload v-model="form.fileIdList" :maxCount="10"></ve-upload>
            <ve-gap size="12"></ve-gap>
            <ve-tag color="orange" title="支持上传jpg、png格式，最多上传10张" />
          </view>
        </ve-form-item>
      </ve-card>
    </ve-form>
    <ve-gap size="60"></ve-gap>

    <ve-bottom-box>
      <view class="bottom-btns">
        <view class="amount">
          付款：
          <text class="amount-num">{{ form.actualAmount }} </text>
          <text class="amount-pic">元</text>
        </view>
        <view class="line"></view>
        <ve-button type="primary" @click="toConfirm" :loading="okLoading" size="long">确认</ve-button>
      </view>
    </ve-bottom-box>
  </view>
</template>

<script setup>
  // 结算组件，支持三种类型 结算类型为【付款】
  // 1保养 2维修 3年检
  import { ref } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { getConfirmAssetFeeDetail, confirmAssetFee } from '@/api/asset/asset-fee'
  import { getAccountByPageData, getAccountByWayAndType } from '@/api/dict/detail'
  import useFormFold from '@/hooks/useFormFold'
  import useToast from '@/hooks/useToast'
  import FeeTable from './components/fee-table.vue'

  const accountList = ref([])
  /**
   * 1保养 2维修 3年检
   */
  const veFormRef = ref(null)
  const form = ref({})
  const rules = ref({
    paymentTime: {
      required: true,
      message: '请选择',
    },
    paymentWay: {
      required: true,
      message: '请选择',
    },
    customerName: {
      required: true,
      message: '请输入',
    },
  })

  const { foldStatus, foldValidate } = useFormFold([
    {
      key: 'fold1',
      props: ['paymentTime', 'paymentWay', 'customerName', 'account', 'deductionOrderId'],
    },
  ])

  // 获取支付方式列表
  const paywayEnum = ref([])
  const initPayType = async (costType) => {
    paywayEnum.value = []
    getAccountByPageData({ type: costType == 0 ? 0 : 1 }).then((res) => {
      // 过滤
      res.result.forEach((i) => {
        if (i.way != '1' && i.way != '2' && i.way != '3' && i.way != '4' && i.way != '5') {
          paywayEnum.value.push({
            value: i.way,
            label: i.wayStr,
          })
        }
      })
    })
  }

  // 获取账号
  const typeChange = (e) => {
    form.value.account = ''
    paywayEnum.value.forEach((el) => {
      if (el.value == e) {
        getAccountByWayAndType({ way: Number(el.value), type: costType.value }).then((res) => {
          var children = res.result.map((childItem) => {
            return {
              value: childItem.id,
              label: form.value.paymentWay != -1 ? childItem.account + '_' + childItem.bank : childItem.bank,
            }
          })
          accountList.value = children
        })
      }
    })
  }
  // 修改供应商
  const customerChange = (val, option) => {
    form.value.customerName = option.supplierName
    form.value.customerId = option.id
  }

  // 提交
  const okLoading = ref(false)
  const toConfirm = () => {
    okLoading.value = true
    veFormRef.value.validate((valid, errors) => {
      if (valid) {
        const parmas = {
          ...form.value,
        }
        confirmAssetFee(parmas)
          .then((res) => {
            okLoading.value = false
            if (res.code == 200) {
              useToast({
                title: '确认成功',
              }).then(() => {
                // 维修 年检 保养刷新list
                uni.$emit('loadData')
                uni.$emit('carInspect_getList')
                uni.$emit('carMaintenance_getList')
                uni.navigateBack()
              })
            }
          })
          .finally(() => {
            okLoading.value = false
          })
      } else {
        foldValidate(errors)
        okLoading.value = false
        console.log('验证失败', errors)
      }
    })
  }

  const costType = ref(null)
  const feeCategory = ref('')
  const initFormData = (ids, fee, actualAmount) => {
    costType.value = fee.costType
    feeCategory.value = fee.feeCategory

    form.value = {
      idList: ids,
      paymentTime: fee.createTime,
      actualAmount: actualAmount,
      // 默认供应商
      customerId: fee.supplierId,
      customerName: fee.supplierName,
      customerType: 1,
      customerAccount: undefined,
      settlementRemark: undefined,
      paymentWay: undefined,
      account: undefined,
    }
  }

  const feeRecord = ref({})
  const getFeeDetail = async (idList) => {
    const res = await getConfirmAssetFeeDetail({ idList })
    const { receiveAmount, receivedNotAmount, carAssetFeeList, costType } = res.result
    // 总费用
    feeRecord.value = {
      receiveAmount: Math.abs(receiveAmount),
      receivedNotAmount: Math.abs(receivedNotAmount),
      ...carAssetFeeList[0],
    }
    // 初始化form
    initFormData(idList, carAssetFeeList[0], feeRecord.value.receivedNotAmount)
    initPayType(costType)
  }

  onLoad((options) => {
    // init,获取结算信息
    getFeeDetail([options.id])
  })
</script>

<style lang="scss" scoped>
  .container {
    height: auto;
    min-height: 100%;
    padding: 24rpx;
  }
  .viewports {
    background: #f7f8fa;
    display: flex;
    flex-direction: column;
    padding: 24rpx;
  }
  .status-1 {
    background: #ffece8;
    color: #ff7d00;
    border: 2rpx solid #ff7d00;
    border-radius: 450rpx;
    padding: 0 16rpx;
    height: 40rpx;
    line-height: 40rpx;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
  .status-2 {
    background: #e8f7ff;
    color: #3491fa;
    border: 2rpx solid #3491fa;
    border-radius: 450rpx;
    padding: 0 16rpx;
    height: 40rpx;
    line-height: 40rpx;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
  .status-4 {
    background: #f5e8ff;
    color: #722ed1;
    border: 2rpx solid #722ed1;
    border-radius: 450rpx;
    padding: 0 16rpx;
    height: 40rpx;
    line-height: 40rpx;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
  .line {
    width: 100%;
    background: #d8d8d8;
    height: 1rpx;
  }

  .fee-item {
    overflow-x: scroll;
    margin-top: 24rpx;
    .fee-table {
      width: 800rpx;
      .tlt {
        width: 100%;
        height: 88rpx;
        background: #f7f8fa;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        color: #8491a8;
        font-size: 24rpx;
        view:nth-child(1) {
          width: 320rpx;
          margin-left: 24rpx;
        }
        view:nth-child(2) {
          width: 160rpx;
        }
        view:nth-child(3) {
          width: 320rpx;
        }
      }
      .fee-first {
        width: 100%;
        margin: 32rpx 0 16rpx;
        background: #ffffff;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        color: #191c27;
        font-size: 28rpx;
        view:nth-child(1) {
          width: 320rpx;
          margin-left: 24rpx;
        }
        view:nth-child(2) {
          width: 160rpx;
        }
        view:nth-child(3) {
          width: 320rpx;
        }
      }
      .fee-other {
        margin-left: 22rpx;
        .twice {
          width: calc(100% - 20rpx);
          background: #f7f8fa;
          padding: 0 24rpx 24rpx;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          color: #191c27;
          font-size: 28rpx;
          view {
            margin-top: 24rpx;
          }
          view:nth-child(1) {
            width: 296rpx;
            margin-left: 24rpx;
          }
          view:nth-child(2) {
            width: 160rpx;
          }
          view:nth-child(3) {
            width: 320rpx;
          }
        }
        .third {
          width: calc(100% - 20rpx);
          background: #f7f8fa;
          padding: 0 24rpx 24rpx;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          color: #191c27;
          font-size: 28rpx;
          view:nth-child(1) {
            width: 248rpx;
            margin-left: 48rpx;
          }
          view:nth-child(2) {
            width: 160rpx;
          }
          view:nth-child(3) {
            width: 320rpx;
          }
        }
      }
    }
  }
  .bottom-btns {
    width: 100%;
    display: flex;
    flex-direction: column;
    .amount {
      color: #1e1e1e;
      font-size: 32rpx;
      font-weight: 400;
      display: flex;
      justify-content: flex-start;
      align-items: flex-end;
      margin: 12rpx 0 36rpx;
      .amount-num {
        color: #fe615a;
        font-size: 48rpx;
        font-weight: 600;
        line-height: 1;
      }
      .amount-pic {
        color: #fe615a;
        font-size: 24rpx;
        font-weight: 400;
        margin-left: 8rpx;
      }
    }
    .line {
      width: 100%;
      background: #d8d8d8;
      height: 1rpx;
      margin-bottom: 32rpx;
      transform: scaleY(0.5);
    }
  }
  :deep(.ve_tooltip__popper) {
    width: 420rpx;
    line-height: 38rpx;
    white-space: normal;
  }

  .deduction-order-select {
    width: 100%;
    font-size: 30rpx;
    font-weight: 400;
    color: #191c27;
    line-height: 44rpx;
  }

  .deduction-order-select-amount {
    color: #3072f6;
  }
  .placeholder {
    color: #8491a8;
  }
</style>
